<template>
    <div class="jobTitle-management">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="请输入职位姓名或病历号" clearable @clear="handleSearch"
                @keyup.enter="handleSearch">
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>
            <el-button type="primary" :icon="Plus" @click="handleAddJobTitle">新增职位</el-button>
        </div>

        <!-- 职位列表 -->
        <el-table :data="filteredJobTitles" stripe style="width: 100%" @row-click="handleRowClick">
            <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                :sortable="column.sortable" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="link" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="link" :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination :page="currentPage" :size="pageSize" :total="totalJobTitles" @pagination="handlePagination" />

        <!-- 职位详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="职位详情" size="40%">
            <div v-if="selectedJobTitle">
                <h3>{{ selectedJobTitle.name }} 的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="名称">{{ selectedJobTitle.name }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>

        <!-- 新增/编辑职位对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑职位' : '新增职位'">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { GetJobTitle, PostJobTitle, PutJobTitle, DeleteJobTitle, GetJobTitleByPage } from '@/api/JobTitleService'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import Pagination from '@/components/Pagination/Pagination.vue'
const { t } = useI18n()

const columns = [
    { prop: 'name', label: '姓名', sortable: true }
]

// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: t('cannotBlank', { field: t('name') }), trigger: 'blur' },
        { min: 2, max: 5, message: '职位长度应为 2 到 20 个字符', trigger: 'blur' }
    ]
})

const jobTitles = ref<any>([])
onMounted(async () => {
    const response = await GetJobTitle()
    if (response.code === 200) {
        jobTitles.value = response.data
    }
    else {
        ElMessage.error(response.msg)
    }
})

// 搜索功能
const searchQuery = ref('')
const filteredJobTitles = computed(() => {
    if (!jobTitles.value) {
        return []
    }
    return jobTitles.value.filter(jobTitle =>
        jobTitle.name.includes(searchQuery.value))
})

// 职位详情
const drawerVisible = ref(false)
const selectedJobTitle = ref<any>(null)

// 新增/编辑职位
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref<any>({
    id: 0,
    name: "",
    idNumber: 0,
    gender: "",
    birthDate: new Date(),
    contactPhone: 0,
    address: "",
    departmentID: 2,
})

// 方法
const handleSearch = () => {
    currentPage.value = 1
}

const handleRowClick = (jobTitle) => {
    selectedJobTitle.value = jobTitle
    drawerVisible.value = true
}

const handleAddJobTitle = () => {
    form.value = {
        id: 0,
        name: "",
    }
    isEdit.value = false
    dialogVisible.value = true
}

const handleEdit = (jobTitle) => {
    // form.value = { ...jobTitle }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = {
        id: jobTitle.id,
        name: jobTitle.name,
    }
    isEdit.value = true
    dialogVisible.value = true
}

const handleDelete = (jobTitle) => {
    jobTitles.value = jobTitles.value.filter(p => p.id !== jobTitle.id)
    DeleteJobTitle(jobTitle.id)
}

const formRef = ref<any>(null)

const handleSubmit = () => {
    const request = {
        id: form.value.id,
        name: form.value.name,
    }
    formRef.value.validate(async (valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = jobTitles.value.findIndex(p => p.id === request.id)
                jobTitles.value[index] = { ...request }
                PutJobTitle(request.id, request)
                console.log('编辑职位:', request)
            } else {
                const response = await PostJobTitle(request)
                if (response.code === 200) {
                    jobTitles.value.push({ ...request, id: jobTitles.value.length + 1 })
                }
                else {
                    ElMessage.error(response.msg)
                }
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })
}


// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalJobTitles = computed(() => filteredJobTitles.value.length)

// 分页变化处理
const handlePagination = async ({ page, size }: { page: number, size: number }) => {
    currentPage.value = page
    pageSize.value = size
    // 后端分页
    const response = await GetJobTitleByPage(currentPage.value, pageSize.value)
    if (response.code === 200) {
        jobTitles.value = response.data
    }
    else {
        ElMessage.error(response.msg)
    }
}

</script>

<style scoped>
.jobTitle-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>